package com.bwei.mypaot.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

/**
 * Created by Administrator on 2017/2/12.
 */

public class LetterView extends View {

    private int width;
    private int height;
    private OnLetterSelectListener onLetterSelectListener;
    String b[]={"A","B","C","D","E","F","G","H","I","J","K","L",
            "M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    private String[] city_group_list;
    private int singleHeight;
    private float y;
    private boolean showbg=false;
    private int lastposition=-1;
    public LetterView(Context context) {
        super(context);
    }

    public LetterView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LetterView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = this.getWidth();
        height = this.getHeight();
        //计算单个高度
        singleHeight = height/b.length;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint=new Paint();
        paint.setColor(Color.WHITE);
        paint.setTextSize(18);
        paint.setAntiAlias(true);
        if (showbg){
            canvas.drawColor(Color.YELLOW);

        }
        for (int i = 0; i < b.length; i++) {
            float measuretext=paint.measureText(b[i]);
            canvas.drawText(b[i],width/2-measuretext/2,singleHeight*(i+1),paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
          switch (event.getAction()){
              case MotionEvent.ACTION_DOWN:
              case MotionEvent.ACTION_MOVE:
                  showbg=true;
                  //计算出当前按在那个字母上
                  y = event.getY();
                  int position= (int) (y*b.length/height);
                  Toast.makeText(getContext(),"当前字母"+b[position],Toast.LENGTH_SHORT).show();
                  if (lastposition!=position){
                      onLetterSelectListener.setSelectListener(b[position]);
                  }
                  lastposition=position;
                  break;
              case MotionEvent.ACTION_UP:
                  showbg=false;
                  lastposition=-1;
                  break;

          }

        postInvalidate();
        return true;
    }

    public interface OnLetterSelectListener{
        public void setSelectListener(String s);
    }
    public void setOnLetterSelectListener(OnLetterSelectListener onLetterSelectListener){
        this.onLetterSelectListener=onLetterSelectListener;

    }

}
